document.addEventListener('DOMContentLoaded', () => {
  const form = document.getElementById('uploadForm');
  const searchInput = document.getElementById('searchInput');
  const resultText = document.getElementById('resultText');
  const historyList = document.getElementById('historyList');

  // 表单提交处理
  form.addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const keyword = searchInput.value.trim();
    
    if (keyword) {
        try {
            const response = await fetch('/search', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ keyword })
            });
            
            if (!response.ok) {
                throw new Error(`HTTP错误! 状态码: ${response.status}`);
            }
      
      const data = await response.json();
      resultText.textContent = `分类结果：${data.category || '未识别'}`;
      fetchHistory();
    } catch (error) {
      console.error('上传失败:', error);
      resultText.textContent = '查询失败，请重试';
    }
  }});

  // 获取历史记录
  async function fetchHistory() {
    try {
      const response = await fetch('/history');
      const history = await response.json();
      historyList.innerHTML = history
        .map(item => `<li>${new Date(item.timestamp).toLocaleString()} - ${item.keyword}: ${item.category}</li>`)
        .join('');
    } catch (error) {
      console.error('获取历史记录失败:', error);
    }
  }

  fetchHistory();
});